/**
 * 
 */
package com.podmanager.data;

import java.util.List;

import com.podmanager.RssFeed.RSSParser;
import com.podmanager.RssFeed.RSSPost;
import com.podmanager.file.FileUtility;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.widget.Toast;

/**
 * @author Tony
 *
 */
public class ProcessFeedAsyncTask extends AsyncTask<String, String, Uri /*We can change result type by changing this*/> {

    private Context context;
    private List<RSSPost> episodes;
    private ProgressDialog dialog;

	/**
	 * constructor requires context so that it can access contentresolver
	 */
	public ProcessFeedAsyncTask(Context c) {
		super();
		context = c;
        dialog = new ProgressDialog(context);
	}
        @Override
        protected Uri doInBackground(String... params) {
			ContentValues values = new ContentValues();
			long row_id = this.getLastSubscriptionRowId()+1;
			

			Uri newUri = insertSubscriptionToDatabase(values, params[0], ""+row_id);
			if (newUri==null)return null;
			
			row_id = ContentUris.parseId(newUri);
			
			newUri = insertEpisodesToDatabase(row_id, episodes, newUri);
			
            return newUri;
        }
        
        private Uri insertSubscriptionToDatabase(ContentValues values, String... params) {
			String filePath = FileUtility.getFeedDirectory().getAbsolutePath() + "/" 
					+ FileUtility.getTimeStampedFileName();
			RSSParser rssfeed = new RSSParser(params[0], filePath);

	        this.publishProgress("Downloading Feed...");
			rssfeed.downloadRSS(); 

	        this.publishProgress("Parsing Feed...");
			rssfeed.parseRss();
			episodes = rssfeed.getPostList();

	        this.publishProgress("Downloading Podcast Image...");
			String imageFile = downloadImageFile(rssfeed.getSubscriptionImageUrl(), 
												params[1]);

	        this.publishProgress("Storing Podcast info...");
			values.put(PMDatabase.SUBSCRIPTIONS.SUB_TITLE, rssfeed.getSubscriptionTitle());
			values.put(PMDatabase.SUBSCRIPTIONS.EPISODE_COUNT, episodes.size());
			values.put(PMDatabase.SUBSCRIPTIONS.EPISODES_DOWNLOADED, 0);	// user will not download episodes initially
			values.put(PMDatabase.SUBSCRIPTIONS.SUB_IMAGE_PATH, imageFile);	// downloaded image file
			values.put(PMDatabase.SUBSCRIPTIONS.SUB_IMAGE_URL, rssfeed.getSubscriptionImageUrl());
			values.put(PMDatabase.SUBSCRIPTIONS.URL_FEED, rssfeed.getSubscriptionLink());
			values.put(PMDatabase.SUBSCRIPTIONS.SUB_DESCRIPTION, rssfeed.getSubscriptionDescription());
			values.put(PMDatabase.SUBSCRIPTIONS.SUB_UPDATE_DT, getPubDate(rssfeed));
			
			FileUtility.deleteFile(filePath); // delete rss.xml file
			
			return context.getContentResolver().insert(DBContentProvider.SUBSCRIPTION_URI, values);
        }
        
        private String getPubDate(RSSParser rssfeed) {
        	String date = null;
			try {
				date = new DateConverter().ConvertDate(rssfeed.getSubscriptionPubDate());
			} 
			catch (Exception e) 
			{ 
				date = "";
			}
			return date;
        }
        
        private String downloadImageFile(String imageUrl, String title) {
			String filePath = FileUtility.getImageDirectory().getAbsolutePath() + "/" 
					+ title + ".jpg";
			
        	RSSParser parser = new RSSParser(imageUrl, filePath);
        	parser.downloadRSS();
        	
        	return filePath;
        }
        
        private String downloadImageFile(String imageUrl, String title, long row_id) {
			String filePath = FileUtility.getDirectoryForImages(row_id) 
					+ "/" + title + ".jpg";
			
        	RSSParser parser = new RSSParser(imageUrl, filePath);
        	parser.downloadRSS();
        	
        	return filePath;
        }
        
		private Uri insertEpisodesToDatabase(long row_id, List<RSSPost> episodes, Uri newUri) {
			long episode_row_id = getLastEpisodeRowId() + 1;	// the next insertion row
			long original_episode_row_id=episode_row_id;
			for(RSSPost episode : episodes) {
				String paddedRow=String.format("%4s",episode_row_id-original_episode_row_id);
		        this.publishProgress("Processing Episode "+paddedRow+" of "+episodes.size());
				String imageUrl = downloadImageFile(episode.getThumbnailUrl(), 
													Long.toString(episode_row_id), row_id);
				String podcastFile = FileUtility.getDirectoryForEpisodes(row_id)
													+ "/" + episode_row_id + ".mp3";
				ContentValues values = new ContentValues();
				values.put(PMDatabase.EPISODES.SUB_ROW_ID, row_id);
				values.put(PMDatabase.EPISODES.EPI_TITLE, episode.getTitle());
				values.put(PMDatabase.EPISODES.EPI_DESCRIPTION, episode.getDescription());
				
				String date = new DateConverter().ConvertDate(episode.getPubDate());
				values.put(PMDatabase.EPISODES.EPI_DATE, date);
				
				values.put(PMDatabase.EPISODES.EPI_IMAGE_PATH, imageUrl);
				values.put(PMDatabase.EPISODES.EPI_IMAGE_URL, episode.getThumbnailUrl());
				values.put(PMDatabase.EPISODES.FILE_PATH, podcastFile);		//not sure where file name comes from
				values.put(PMDatabase.EPISODES.FILE_URL, episode.getUrl());
				values.put(PMDatabase.EPISODES.DURATION, 0);					// not sure where to get this
				values.put(PMDatabase.EPISODES.POSITION, 0);
				values.put(PMDatabase.EPISODES.IS_READ, 0);
				values.put(PMDatabase.EPISODES.IS_IN_PLAYLIST, 0);
				
				newUri = context.getContentResolver().insert(DBContentProvider.EPISODES_URI, values);
				episode_row_id++;
			}
			return newUri;
		}      

		private long getLastEpisodeRowId() {
			String[] projection={"MAX(_id)"};
			Cursor c = context.getContentResolver().query(DBContentProvider.EPISODES_URI, projection, null, null, null);
			long returnValue=0;
			c.moveToFirst();
			returnValue=c.getLong(0);
			c.close();
			return returnValue;
		}
		private long getLastSubscriptionRowId() {
			String[] projection={"MAX(_id)"};
			Cursor c = context.getContentResolver().query(DBContentProvider.SUBSCRIPTION_URI, projection, null, null, null);
			long returnValue=0;
			c.moveToFirst();
			returnValue=c.getLong(0);
			c.close();
			return returnValue;
		}

		@Override
        protected void onPostExecute(Uri result) {
	        if (dialog.isShowing()) {
	            dialog.dismiss();
	        }
			if (result == null)
			{		
				AlertDialog.Builder builder = new AlertDialog.Builder(context);

				// 2. Chain together various setter methods to set the dialog characteristics
				builder=builder.setMessage("If you entered the URL manually, make sure it was a valid RSS feed")
				       .setTitle("Error Adding Subscription")
				       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
				    			((Activity)context).finish();}
					});
				builder.show();
			
			}
			else
			{
				Toast.makeText(context, "Subscription Complete", Toast.LENGTH_LONG).show();
				((Activity)context).finish();
			
			}
        }

        @Override
        protected void onPreExecute() {
            this.dialog.setMessage("Initiating");
            this.dialog.show();
        }

    	@Override
    	protected void onProgressUpdate(String... values) {
    		super.onProgressUpdate(values);
    		dialog.setMessage(values[0]);
    	}

}
